unit MVC.Tool;

{$mode ObjFPC}{$H+}

interface

uses
  Classes, SysUtils;

type
  ITool = interface
    function PathFmt(path: string): string;
    function UrlFmt(url: string): string;
    function GetGUID: string;
    function StringFormat(Asrc: string): string;
    function UnicodeEncode(Asrc: string): string;
  end;

  { TTool }

  TTool = class(TInterfacedObject, ITool)
  private

  public
    function PathFmt(path: string): string;
    function UrlFmt(url: string): string;
    function GetGUID: string;
    function StringFormat(Asrc: string): string;
    function UnicodeEncode(Asrc: string): string;
  end;

function IITool: ITool;

implementation

function IITool: ITool;
var
  tool: ITool;
begin
  tool := TTool.Create;
  Result := tool;
end;

function TTool.StringFormat(Asrc: string): string;
var
  s: string;
begin
  s := Asrc.Replace(#7, '\a').Replace(#8, '\b').Replace(#12, '\f');
  s := s.Replace(#9, '\t').Replace(#11, '\v').Replace(#92, '\\');
  s := s.Replace(#39, '''').Replace(#34, '\"').Replace(#63, '\?');
  s := s.Replace(#13, '\\r').Replace(#10, '\\n');
  Result := s;

end;

function IsHZ(ch: widechar): boolean;
var
  i: integer;
begin
  i := Ord(ch);
  if (i < 19968) or (i > 40869) then
    Result := False
  else
    Result := True;
end;

function TTool.UnicodeEncode(Asrc: string): string;
var
  w: integer;
  hz: WideString;
  i: integer;
  s: AnsiString;
begin

  hz := StringFormat(Asrc);
  for i := 1 to Length(hz) do
  begin
    if IsHZ(hz[i]) then
    begin
      w := Ord(hz[i]);
      s := s + '\u' + IntToHex(w, 4);
    end
    else
      s := s + hz[i];
  end;
  Result := s;
end;

function TTool.GetGUID: string;
var
  LTep: TGUID;
  sGUID: string;
begin
  CreateGUID(LTep);
  sGUID := GUIDToString(LTep);
  sGUID := StringReplace(sGUID, '-', '', [rfReplaceAll]);
  sGUID := Copy(sGUID, 2, Length(sGUID) - 2);
  Result := sGUID;
end;

function TTool.PathFmt(path: string): string;
var
  ret: string;
begin
  {$IFDEF MSWINDOWS}
  ret := path.Replace('\\', '\').Replace('//', '\').Replace('/', '\');
  {$ELSE}
  ret := path.Replace('\\', '/').Replace('//', '/').Replace('\', '/');
  {$ENDIF}
  Result := ret;
end;

function TTool.UrlFmt(url: string): string;
var
  ret: string;
begin
  ret := url.Replace('\\', '/').Replace('//', '/').Replace('\', '/');
  Result := ret;
end;

end.
